<template>
    <div class="main-content">
        <ElForm
            ref="searchFormRef"
            :model="searchForm"
            inline
            class="search-form"
            label-width="68px"
            label-position="left">

            <ElFormItem label="角色名称" prop="roleName">
                <ElInput
                    v-model="searchForm.roleName"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="角色状态" prop="status">
                <ElSelect
                    v-model="searchForm.status"
                    size="default"
                    placeholder="请选择"
                >
                    <ElOption
                        v-for="item in statusOps"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></ElOption>
                </ElSelect>
            </ElFormItem>


            <ElFormItem>
                <ElButton
                    size="default"
                    color="#4371EE"
                    @click="reset(false)"
                >
                    查询
                </ElButton>
                <ElButton
                    size="default"
                    plain=""
                    @click="reset(true)"
                >
                    重置
                </ElButton>
            </ElFormItem>
        </ElForm>
            <!-- </ElCol> -->
            <div class="btns">
                <ElButton

                    class="add-btn"
                    color="#4371EE"
                    size="default"
                    :icon="Plus"
                    @click="addShow = true"
                >
                    添加角色
                </ElButton>
            </div>
            <ElTable
                border
                id="userTable"
                class="table"
                :data="tableData"
                :style="{ height: `${maxTableHeight}px`, overflow: 'auto' }"
            >
                <ElTableColumn prop="roleName" label="角色名称" />

                <ElTableColumn prop="roleDesc" label="角色说明" />
                <ElTableColumn prop="status" label="状态" >
                    <template #default="scope">
                        {{ statusOps.find(({ value }) => value == scope.row.status).label }}
                    </template>
                </ElTableColumn>
                <ElTableColumn prop="createTime" label="创建时间" />
                <ElTableColumn prop="updateTime" label="更新时间" />
                <ElTableColumn  fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <ElButton

                            link
                            type="text"
                            size="default"
                            @click="editFun(scope.row)"
                        >
                            修改
                        </ElButton>
                        <ElButton

                            link
                            type="text"
                            size="default"
                            @click="handleEnable(scope.row)"
                            >
                            {{ scope.row.status == 0 ? '启用' : '禁用'}}
                        </ElButton>
                        <ElButton  link type="text" size="default" @click="handleDelete(scope.row)">
                            删除
                        </ElButton>

                    </template>
                </ElTableColumn>
            </ElTable>

            <ElPagination
                class="pagination"
                background
                layout="total,sizes,prev, pager, next,jumper"
                :total="total"
                :current-page="searchForm.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="searchForm.pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />

            <!--新增或编辑角色-->
            <ElDialog   class="main-dialog" v-model="addShow"  :title="!addForm.roleId ? '添加角色' : '修改角色' " width="480px">
                <div class="dialog-form">
                    <ElForm
                        ref="addFormRef"
                        :model="addForm"
                        :rules="rules"
                        label-width="80px"
                        label-position="left"
                    >

                        <ElFormItem label="角色名称" prop="roleName">
                            <el-input v-model="addForm.roleName" size="default" placeholder="请输入角色名"  />
                        </ElFormItem>

                        <ElFormItem label="角色名称" class="authItem" prop="roleDesc">
                            <el-input type="textarea" :rows="5" v-model="addForm.roleDesc" size="default" placeholder="请输入角色说明"  />
                        </ElFormItem>
                        <ElFormItem label="数据权限" class="authItem" prop="dataAuth">
                            <ElCheckboxGroup v-model="addForm.dataAuth">
                                <ElCheckbox
                                v-for="item in dataList"
                                :key="item.status"
                                :label="item.status">
                                    {{ item.title }}
                                </ElCheckbox>
                            </ElCheckboxGroup>
                        </ElFormItem>
                        <ElFormItem label="权限设置" class="authItem" props="moduleIds">
                            <el-tree
                            ref="treeRef"
                            node-key="id"
                            :data="authList"
                            show-checkbox
                            :default-checked-keys="defaultKeys"
                            @check-change="handleCheckChange"
                        />
                        </ElFormItem>
                    </ElForm>
                </div>
                <template #footer>
                    <span  class="dialog-footer">
                        <ElButton size="default" @click="addShow = false">取 消</ElButton>
                        <ElButton color="#4371EE" size="default" @click="submitForm(addFormRef)">提 交</ElButton>
                    </span>
                </template>

            </ElDialog>



    </div>
</template>

<script setup lang="ts">
import useTableSetting from '@/hooks/useTableSetting';
import { ref, onMounted, reactive, nextTick, watch } from 'vue';


import { ElMessage, ElTree, FormInstance, ElMessageBox, ElCheckboxGroup, ElCheckbox } from 'element-plus';

import { getFlatDeepTreeData } from '@/utils/common';
import { Search, Plus } from '@element-plus/icons-vue';
import { validateForm, getFlatArry } from '@/helper/index';
import authList from '@/router/auth.ts';
import { addRole, editRole, delRole, roleList,listAllModule, listModuleByRoleId, getAllDataStatus} from '@/api/index.ts';

const treeRef = ref<InstanceType<typeof ElTree>>();
const defaultKeys = ref([]);
const tableData: any = ref();
const statusOps = [
    { label: '禁用', value: 0 },
    { label: '启用', value: 1 },

];

const dataList = ref([]);
const getDataStatus = async () => {
    dataList.value = await getAllDataStatus();
};

getDataStatus();

listAllModule({subSystem: 0});
const searchFormRef = ref<FormInstance>(null);

const details = ref({});


const searchForm = reactive<searchFormType>({

    roleName: '',

    status: '',
    pageNum: 1,
    pageSize: 20,
});
const total = ref<number>(0);


const handleCheckChange = (
    data: Tree,
    checked: boolean,
    indeterminate: boolean
) => {
    console.log(data, checked, indeterminate);
};



const rules = reactive({
    roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
});


const getList = async () => {
    try {
        const res: any = await roleList(searchForm);
        tableData.value = res.list;
        total.value = res.total;
    } catch (err) {}
};

const handleDelete = async (row) => {
    await ElMessageBox.confirm('确认要删除吗？', '提示', {
        confirmButtonText: '确  定',
        cancelButtonText: '取  消',
        type: 'warning'
    });
    await delRole({ roleId: row.roleId});
    ElMessage.success('删除成功！');
    reset();
};

const goDetail = (row) => {
    details.value = JSON.parse(JSON.stringify(row));
};

const reset = (reset: boolean) => {
    if(reset) {
        searchFormRef.value.resetFields();
    }
    searchForm.pageNum = 1;
    getList();
};

const handleSizeChange = (rows: number) => {
    searchForm.pageNum = 1;
    searchForm.pageSize = rows;
    getList();
};
const handleCurrentChange = (page: number) => {
    searchForm.pageNum = page;
    getList();
};


const addShow = ref<boolean>(false);
const addFormRef = ref<FormInstance>(null);
const addForm = reactive<addRoleType>({
    roleId: '',
    addTime: '',
    dataAuth: [],
    roleDesc: '',
    moduleIds: [],
    roleName: '',
    status:''
});

const resetForm = (form) => {
    Object.keys(form).forEach(key => addForm[key] = Array.isArray(addForm[key]) ? [] : '');
};

watch(
    addShow,
    val => {
        if(!val) {
            addFormRef.value.clearValidate();
            resetForm(addForm);
            defaultKeys.value = [];
        }
    }
);

const submitForm = async (formEl: FormInstance | undefined) => {
    addForm.moduleIds = treeRef.value!.getCheckedKeys(true);
    const params = {
        ...addForm,
        moduleIds: addForm.moduleIds.join(','),
        dataConfig: addForm.dataAuth.join(',')
    };
    await validateForm(formEl);
    addForm.roleId ? await editRole(params) : await addRole(params);

    ElMessage.success('操作成功！');
    addShow.value = false;
    reset();
};



const editFun = async (row: any) => {
    const authes = await listModuleByRoleId({ roleId: row.roleId});
    addForm.moduleIds = getFlatArry(authes);

    addShow.value = true;
    await nextTick();
    treeRef.value!.setCheckedKeys(addForm.moduleIds, true);
    Object.keys(row).forEach(key => {
        if(key in addForm) {
            addForm[key] = row[key];
        }
    });
    if(row.dataConfig){
        addForm.dataAuth = row.dataConfig.split(',').map(item => +item);
    }

    await nextTick();
};

const handleEnable  = async (row: any) => {
    const params = {
        roleId : row.roleId,
        status : 1- row.status
    }
    await editRole(params)
    ElMessage.success(row.status === 0 ? '启用成功' : '禁用成功');
    getList()
};


onMounted(() => {

    getList();
});
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'userTable', offsetBottom: 92 });
</script>

<style scoped lang="scss">
.main-content > .btns{
    margin:10px 0 20px;
}
.authItem{
    align-items: flex-start;
}
.search-form{
   ::v-deep(){
    .el-input,.el-select{
        width: 265px !important;
    }
   }
}
</style>

